package com.alinesno.cloud.initializr.starter.common.impl;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.alinesno.cloud.common.facade.mapper.entity.BaseEntity;
import com.alinesno.cloud.initializr.starter.codegen.entity.GenTableColumn;
import com.google.common.base.CaseFormat;

/**
 * 生成表实体类时过滤父类字段功能
 *
 * @author zhuogm
 */
public class SuperEntityFilter {

	/**
	 * 应用过滤规则
	 *
	 * @return 过滤后的结果
	 */
	public List<GenTableColumn> apply(List<GenTableColumn> columns) {
		List<String> baseFields = resolveSuperEntity();
		List<GenTableColumn> result = new ArrayList<>();
		for (GenTableColumn f : columns) {
			if (!baseFields.contains(f.getColumnName())) {
				result.add(f);
			}
		}
		return result;
	}

	/**
	 * 解析实体类父类字段并装换成下划线风格
	 */
	private List<String> resolveSuperEntity() {
		Class<BaseEntity> baseEntityClass = BaseEntity.class;
		Field[] fields = baseEntityClass.getDeclaredFields();
		return Arrays.stream(fields).map(this::transFormer).collect(Collectors.toList());
	}

	private String transFormer(Field field) {
		if (field == null) {
			throw new NullPointerException();
		}
		return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, field.getName());
	}
}
